<template>
  <j-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :destroyOnClose="true"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane tab="基本信息" key="1">
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-auto-complete
                    placeholder="请输入客户名称"
                    v-decorator="['customerName', validatorRules.customerName]"
                    :dropdownMatchSelectWidth="false"
                    @search="handleCustomerSearch"
                    @select="handleCustomerSelect"
                    @change="handleCustomerNameChange"
                    :disabled="disableSubmit"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    optionLabelProp="value"
                  >
                    <template slot="dataSource">
                      <a-select-option v-for="item in customerSuggestions" :key="item.key" :value="item.value">
                        <div>
                          <div>{{ item.label }}</div>
                          <div style="color: #999; font-size: 12px">
                            {{ item.customer.customerCode || '无编码' }} |
                            {{ item.customer.contactPerson || '无联系人' }} |
                            {{ item.customer.contactPhone || '无电话' }}
                          </div>
                        </div>
                      </a-select-option>
                    </template>
                    <a-input />
                  </a-auto-complete>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="系统自动生成" v-decorator="['customerCode']" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['customerType', validatorRules.customerType]"
                    :trigger-change="true"
                    dictCode="customer_type"
                    placeholder="请选择客户类型"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['industry']"
                    :trigger-change="true"
                    dictCode="industry_type"
                    placeholder="请选择所属行业"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['customerSource']"
                    :trigger-change="true"
                    dictCode="customer_source"
                    placeholder="请选择客户来源"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="信用等级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['creditRating']"
                    :trigger-change="true"
                    dictCode="credit_rating"
                    placeholder="请选择信用等级"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="跟进状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['followUpStatus']"
                    :trigger-change="true"
                    dictCode="follow_up_status"
                    placeholder="请选择跟进状态"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="跟进人员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-select-user-by-dep v-decorator="['followUpPerson']" :disabled="disableSubmit" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="省市区" :labelCol="{ span: 3 }" :wrapperCol="{ span: 19 }">
                  <j-area-linkage
                    type="cascader"
                    v-decorator="['area', validatorRules.area]"
                    @change="areaChange"
                    :disabled="disableSubmit"
                    ref="areaLinkage"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="详细地址" :labelCol="{ span: 3 }" :wrapperCol="{ span: 19 }">
                  <a-textarea
                    placeholder="请输入详细地址"
                    v-decorator="['address']"
                    :rows="2"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>

        <a-tab-pane tab="联系信息" key="2">
          <a-form :form="form">
            <a-row>
          <a-col :span="12">
            <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-auto-complete
                    placeholder="请输入联系人姓名"
                    v-decorator="['contactPerson', validatorRules.contactPerson]"
                    :dropdownMatchSelectWidth="false"
                    @search="handleContactSearch"
                    @select="handleContactSelect"
                    @change="handleContactPersonChange"
                    :disabled="disableSubmit"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    optionLabelProp="value"
                  >
                    <template slot="dataSource">
                      <a-select-option v-for="item in contactSuggestions" :key="item.key" :value="item.value">
                        <div>
                          <div>{{ item.contactName || item.value }}</div>
                          <div style="color: #999; font-size: 12px">
                            {{ item.phone || '无电话' }} | {{ item.email || '无邮箱' }}
                          </div>
                        </div>
                      </a-select-option>
                    </template>
                    <a-input />
                  </a-auto-complete>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入职位" v-decorator="['position']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input
                    placeholder="请输入联系电话"
                    v-decorator="['contactPhone', validatorRules.contactPhone]"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input
                    placeholder="请输入手机号码"
                    v-decorator="['mobilePhone', validatorRules.mobilePhone]"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电子邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input
                    placeholder="请输入电子邮箱"
                    v-decorator="['email', validatorRules.email]"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="QQ/微信" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入QQ或微信" v-decorator="['socialContact']" :disabled="disableSubmit" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-decorator="['gender']"
                    :trigger-change="true"
                    dictCode="sex"
                    placeholder="请选择性别"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker style="width: 100%" v-decorator="['birthday']" :disabled="disableSubmit" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>

        <a-tab-pane tab="财务信息" key="3">
          <a-form :form="form">
            <a-row>
          <a-col :span="12">
            <a-form-item label="开户银行" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入开户银行" v-decorator="['bankName']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开户支行" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入开户支行" v-decorator="['bankBranch']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入银行账号" v-decorator="['bankAccount']" :disabled="disableSubmit" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="账户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入账户名称" v-decorator="['accountName']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="纳税人识别号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入纳税人识别号" v-decorator="['taxNumber']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="发票抬头" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入发票抬头" v-decorator="['invoiceTitle']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="信用额度" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    placeholder="请输入信用额度"
                    v-decorator="['creditLimit', { initialValue: 0 }]"
                    :min="0"
                    :step="1000"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
              <a-col :span="12">
                <a-form-item label="账期(天)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    placeholder="请输入账期天数"
                    v-decorator="['paymentTerm', { initialValue: 0 }]"
                    :min="0"
                    :disabled="disableSubmit"
                  />
            </a-form-item>
          </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>

        <a-tab-pane tab="备注信息" key="4">
          <a-form :form="form">
            <a-row>
          <a-col :span="24">
                <a-form-item label="备注" :labelCol="{ span: 3 }" :wrapperCol="{ span: 19 }">
                  <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="6" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    
    <!-- 相似客户提示弹窗 -->
    <a-modal
      :title="'发现相似客户'"
      :width="800"
      :visible="similarCustomerVisible"
      :confirmLoading="confirmLoading"
      @ok="handleSimilarCustomerOk"
      @cancel="handleSimilarCustomerCancel"
    >
      <a-alert
        type="warning"
        message="系统发现可能存在相似的客户信息，请确认是否继续添加？"
        style="margin-bottom: 16px"
      />
      <a-table :columns="similarColumns" :dataSource="similarCustomers" :pagination="false" :scroll="{ y: 240 }">
        <template slot="similarity" slot-scope="text">
          <a-progress :percent="text" size="small" status="active" :strokeColor="getSimilarityColor(text)" />
        </template>
      </a-table>
    </a-modal>
  </j-modal>
</template>

<script>
  import { customerAdd, customerEdit } from '@/api/crm'
  import JAreaLinkage from '@/components/jeecg/JAreaLinkage'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import pick from 'lodash.pick'
  import { validateEmail, validateMobile } from '@/utils/validate'
import { getAction, postAction } from '@/api/manage'
import { isNotEmpty } from '@/utils/util'
import dayjs from 'dayjs'
import moment from 'moment'
import Area from '@/components/_util/Area'

  export default {
  name: 'CustomerModal',
    components: {
      JAreaLinkage,
    JDictSelectTag,
    JSelectUserByDep,
    },
    data() {
      return {
      title: '操作',
      width: 1000,
        visible: false,
        model: {},
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          customerName: { 
          rules: [{ required: true, message: '请输入客户名称!' }],
          },
          customerType: { 
          rules: [{ required: true, message: '请选择客户类型!' }],
          },
          contactPerson: { 
          rules: [{ required: true, message: '请输入联系人!' }],
          },
          contactPhone: { 
          rules: [{ required: true, message: '请输入联系电话!' }, { validator: this.validatePhone }],
        },
        mobilePhone: {
          rules: [{ validator: this.validateMobile }],
          },
          email: { 
          rules: [{ validator: this.validateEmail }],
          },
          area: {
          rules: [{ required: true, message: '请选择省市区!' }],
        },
        },
        disableSubmit: false,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        provinceName: '',
        cityName: '',
      areaName: '',
      // 客户名称建议列表
      customerSuggestions: [],
      // 联系人建议列表
      contactSuggestions: [],
      // 相似客户弹窗
      similarCustomerVisible: false,
      similarCustomers: [],
      similarColumns: [
        {
          title: '客户编码',
          dataIndex: 'customer.customerCode',
          align: 'center',
          width: 120,
        },
        {
          title: '客户名称',
          dataIndex: 'customer.customerName',
          align: 'center',
          width: 200,
        },
        {
          title: '联系人',
          dataIndex: 'customer.contactPerson',
          align: 'center',
          width: 120,
        },
        {
          title: '电话',
          dataIndex: 'customer.phone',
          align: 'center',
          width: 120,
        },
        {
          title: '区域',
          dataIndex: 'customer.area',
          align: 'center',
          width: 180,
          customRender: (text, record) => {
            const province = record.customer.provinceName || ''
            const city = record.customer.cityName || ''
            const area = record.customer.areaName || ''

            // 如果所有地区名称都为空，但有编码，则尝试从编码获取名称
            if (
              !province &&
              !city &&
              !area &&
              (record.customer.provinceCode || record.customer.cityCode || record.customer.areaCode)
            ) {
              let areaNames = []
              // 尝试从this.pcaa获取地区名称
              try {
                if (record.customer.provinceCode) {
                  const provinceData = this.$Jpcaa[record.customer.provinceCode]
                  if (provinceData && typeof provinceData === 'string') {
                    areaNames.push(provinceData)
                  }

                  if (record.customer.cityCode && provinceData) {
                    const cityData = this.$Jpcaa[record.customer.provinceCode][record.customer.cityCode]
                    if (cityData && typeof cityData === 'string') {
                      areaNames.push(cityData)
                    }

                    if (record.customer.areaCode && cityData) {
                      const areaData =
                        this.$Jpcaa[record.customer.provinceCode][record.customer.cityCode][record.customer.areaCode]
                      if (areaData && typeof areaData === 'string') {
                        areaNames.push(areaData)
                      }
                    }
                  }
                }

                if (areaNames.length > 0) {
                  return areaNames.join('/')
                }
              } catch (error) {
                console.error('解析地区编码失败:', error)
              }
            }

            // 如果有任何名称存在，就使用名称
            if (province || city || area) {
              return province + (city ? '/' + city : '') + (area ? '/' + area : '')
            }

            // 如果以上都失败，使用编码作为备选显示
            const provinceCode = record.customer.provinceCode || ''
            const cityCode = record.customer.cityCode || ''
            const areaCode = record.customer.areaCode || ''

            if (provinceCode || cityCode || areaCode) {
              return provinceCode + (cityCode ? '/' + cityCode : '') + (areaCode ? '/' + areaCode : '')
            }

            return '未设置区域'
          },
        },
        {
          title: '相似度',
          dataIndex: 'similarity',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'similarity' },
        },
      ],
      isAdd: false, // 新增标志
      checkUniqueTimer: null, // 防抖定时器
      }
    },
    methods: {
      add() {
      this.isAdd = true
      this.edit({})
      },
      edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.isAdd = !record.id // 根据id判断是否为新增

      console.log('编辑客户数据:', record)

      // 保存省市区代码以便JAreaLinkage组件使用
        if (record.provinceCode) {
        this.provinceCode = record.provinceCode
        this.provinceName = record.provinceName || ''
        this.cityCode = record.cityCode || ''
        this.cityName = record.cityName || ''
        this.areaCode = record.areaCode || ''
        this.areaName = record.areaName || ''

        // 构建区域编码数组用于表单设置
        const areaArray = [this.provinceCode]
        if (this.cityCode) {
          areaArray.push(this.cityCode)
          if (this.areaCode) {
            areaArray.push(this.areaCode)
          }
        }
        this.model.area = areaArray
        
        console.log('设置省市区数据:', {
          provinceCode: this.provinceCode,
          cityCode: this.cityCode, 
          areaCode: this.areaCode,
          area数组: areaArray
        })
        }
        
        this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'customerName',
            'customerCode',
            'customerType',
            'industry',
            'customerSource',
            'creditRating',
            'followUpStatus',
            'followUpPerson',
            'contactPerson',
            'position',
            'contactPhone',
            'mobilePhone',
            'email',
            'socialContact',
            'gender',
            'birthday',
            'bankName',
            'bankBranch',
            'bankAccount',
            'accountName',
            'taxNumber',
            'invoiceTitle',
            'creditLimit',
            'paymentTerm',
            'address',
            'remark',
            'area'
          )
        )
        
        // 表单设置完成后记录日志
        setTimeout(() => {
          this.logAreaData()
        }, 100)
      })
      },
      close() {
      this.$emit('close')
      this.visible = false
      },
      handleOk() {
      const that = this
        if (this.disableSubmit) {
        this.close()
        return
        }
        
        this.form.validateFields((err, values) => {
          if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          console.log('formData', formData)

          // 处理日期格式
          if (values.birthday) {
            formData.birthday = values.birthday.format('YYYY-MM-DD')
          }
            
            // 处理省市区数据
          if (values.area) {
            // 如果area是数组形式，表示级联选择器的值
            if (Array.isArray(values.area)) {
              formData.provinceCode = values.area[0] || ''
              formData.cityCode = values.area.length > 1 ? values.area[1] : ''
              formData.areaCode = values.area.length > 2 ? values.area[2] : ''
              
              // 尝试获取对应的名称
              try {
                if (formData.provinceCode && this.$Jpcaa && this.$Jpcaa['86']) {
                  formData.provinceName = this.$Jpcaa['86'][formData.provinceCode] || ''
                }
                
                if (formData.provinceCode && formData.cityCode && this.$Jpcaa && this.$Jpcaa[formData.provinceCode]) {
                  formData.cityName = this.$Jpcaa[formData.provinceCode][formData.cityCode] || ''
                }
                
                if (formData.provinceCode && formData.cityCode && formData.areaCode && 
                    this.$Jpcaa && this.$Jpcaa[formData.provinceCode] && 
                    this.$Jpcaa[formData.provinceCode][formData.cityCode]) {
                  formData.areaName = this.$Jpcaa[formData.provinceCode][formData.cityCode][formData.areaCode] || ''
                }
              } catch (e) {
                console.error('获取省市区名称失败:', e)
              }
            } 
            // 如果没有设置，确保所有省市区信息都为空
            else if (!values.area) {
              formData.provinceCode = ''
              formData.provinceName = ''
              formData.cityCode = ''
              formData.cityName = ''
              formData.areaCode = ''
              formData.areaName = ''
            }
          }

          // 如果使用了组件内部的provinceCode等变量，确保它们优先被使用
          if (this.provinceCode) {
            formData.provinceCode = this.provinceCode
            formData.provinceName = this.provinceName || ''
          }
          if (this.cityCode) {
            formData.cityCode = this.cityCode
            formData.cityName = this.cityName || ''
          }
          if (this.areaCode) {
            formData.areaCode = this.areaCode
            formData.areaName = this.areaName || ''
          }

          // 初始化CrmCustomerVO对象
          let customerVO = {
            // 基本信息
            id: formData.id,
            customerCode: formData.customerCode,
            customerName: formData.customerName,
            customerType: formData.customerType,
            industry: formData.industry,
            customerSource: formData.customerSource,
            creditRating: formData.creditRating,
            followUpStatus: formData.followUpStatus,
            followUpPerson: formData.followUpPerson,
            provinceCode: formData.provinceCode,
            provinceName: formData.provinceName,
            cityCode: formData.cityCode,
            cityName: formData.cityName,
            areaCode: formData.areaCode,
            areaName: formData.areaName,
            address: formData.address,

            // 联系信息
            contactPerson: formData.contactPerson,
            position: formData.position,
            contactPhone: formData.contactPhone,
            mobilePhone: formData.mobilePhone,
            email: formData.email,
            socialContact: formData.socialContact,
            gender: formData.gender,
            birthday: formData.birthday,

            // 财务信息
            bankName: formData.bankName,
            bankBranch: formData.bankBranch,
            bankAccount: formData.bankAccount,
            accountName: formData.accountName,
            taxNumber: formData.taxNumber,
            invoiceTitle: formData.invoiceTitle,
            creditLimit: formData.creditLimit,
            paymentTerm: formData.paymentTerm,

            // 备注信息
            remark: formData.remark,

            // 初始化空联系人和项目列表
            contactList: [],
            projectList: [],
          }

          let obj
            if (!this.model.id) {
            obj = customerAdd(customerVO)
            } else {
            obj = customerEdit(customerVO)
            }
            
          obj
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
      },
      handleCancel() {
      this.close()
      },
      validatePhone(rule, value, callback) {
      if (value && !/^(\d{3,4}-?)?\d{7,8}$/.test(value)) {
        callback('请输入正确的电话号码!')
      } else {
        callback()
      }
    },
    validateMobile(rule, value, callback) {
        if (value && !validateMobile(value)) {
        callback('请输入正确的手机号码!')
        } else {
        callback()
        }
      },
      validateEmail(rule, value, callback) {
        if (value && !validateEmail(value)) {
        callback('请输入正确的电子邮箱!')
        } else {
        callback()
        }
      },
      areaChange(values, labels) {
      //当前values是区编号字符串，通过区编号反推城、市编号 以及获得对应的名称
      console.log('地区选择变更 - 原始值:', values, labels)

      if (!values) {
        // 清空选择
        this.provinceCode = ''
        this.provinceName = ''
        this.cityCode = ''
        this.cityName = ''
        this.areaCode = ''
        this.areaName = ''
        return
      }

      // 判断是否选择了区级信息
      const isAreaSelected = typeof values === 'string' && values.length > 0

      if (isAreaSelected) {
        // 获取区级编码
        this.areaCode = values

        // 根据区编号反推城市和省编号
        if (this.$Jpcaa) {
          try {
            // 从Area数据中查找区域信息
            const area = new Area(this.$Jpcaa)
            if (area && area.pca) {
              // 获取区级数据
              const areaData = area.pca.find((item) => item.id === this.areaCode && item.index === 3)

              if (areaData) {
                // 获取区名称
                this.areaName = areaData.text

                // 获取城市编码
                this.cityCode = areaData.pid

                // 获取城市数据
                const cityData = area.pca.find((item) => item.id === this.cityCode && item.index === 2)
                if (cityData) {
                  // 获取城市名称
                  this.cityName = cityData.text

                  // 获取省级编码
                  this.provinceCode = cityData.pid

                  // 获取省级数据
                  const provinceData = area.pca.find((item) => item.id === this.provinceCode && item.index === 1)
                  if (provinceData) {
                    // 获取省名称
                    this.provinceName = provinceData.text
                  }
                }
              } else {
                // 如果找不到区级数据，尝试使用反推方法
                const codes = area.getRealCode(this.areaCode)
                if (codes && codes.length > 0) {
                  if (codes.length >= 1) this.provinceCode = codes[0]
                  if (codes.length >= 2) this.cityCode = codes[1]
                  if (codes.length >= 3) this.areaCode = codes[2]

                  // 获取名称
                  this.inferAreaNamesFromCodes()
                }
              }
            }
          } catch (error) {
            console.error('反推区域编码失败:', error)
            // 如果反推失败，尝试从labels获取
            if (labels) {
              this.areaName = labels
            }
          }
        }

        // 如果区域名称已获取但省市信息未获取，使用常规方法获取
        if (this.areaName && (!this.provinceName || !this.cityName)) {
          this.getAreaNamesByCodes()
        }

        // 更新表单的area字段值为完整的省市区编码数组
        if (this.provinceCode) {
          const areaArray = [this.provinceCode]
          if (this.cityCode) {
            areaArray.push(this.cityCode)
            if (this.areaCode) {
              areaArray.push(this.areaCode)
            }
          }
          this.form.setFieldsValue({ area: areaArray })
        }

        console.log('地区选择变更 - 处理后:', {
          provinceCode: this.provinceCode,
          provinceName: this.provinceName,
          cityCode: this.cityCode,
          cityName: this.cityName,
          areaCode: this.areaCode,
          areaName: this.areaName,
        })
      } else {
        // 如果values是数组形式，说明使用了级联选择器
        if (Array.isArray(values) && values.length > 0) {
          this.provinceCode = values[0] || ''
          this.cityCode = values.length > 1 ? values[1] : ''
          this.areaCode = values.length > 2 ? values[2] : ''

          // 初始化省市区名称为空
          this.provinceName = ''
          this.cityName = ''
          this.areaName = ''

          // 如果labels是有效数组，从labels获取名称
          if (Array.isArray(labels) && labels.length > 0) {
            this.provinceName = labels[0] || ''
            this.cityName = labels.length > 1 ? labels[1] : ''
            this.areaName = labels.length > 2 ? labels[2] : ''
          }

          // 尝试获取完整的省市区名称
          this.inferAreaNamesFromCodes()
        }
      }
    },

    // 根据省市区编码获取对应的名称
    getAreaNamesByCodes() {
      if (!this.$Jpcaa) {
        console.warn('地区数据未加载，无法获取省市区名称')
        return
      }

      try {
        // 获取省份名称
        if (this.provinceCode && !this.provinceName) {
          const provinceData = this.$Jpcaa[this.provinceCode]
          if (typeof provinceData === 'string') {
            this.provinceName = provinceData
          } else if (provinceData) {
            console.log('省级数据已找到，但不是字符串格式')
          }
        }

        // 获取城市名称
        if (this.provinceCode && this.cityCode && !this.cityName) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityData = provinceData[this.cityCode]
              if (typeof cityData === 'string') {
                this.cityName = cityData
              } else if (cityData) {
                console.log('市级数据已找到，但不是字符串格式')
              }
            }
          } catch (e) {
            console.warn('获取城市名称失败:', e)
          }
        }

        // 获取区域名称
        if (this.provinceCode && this.cityCode && this.areaCode && !this.areaName) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityData = provinceData[this.cityCode]
              if (cityData && typeof cityData === 'object') {
                const areaData = cityData[this.areaCode]
                if (typeof areaData === 'string') {
                  this.areaName = areaData
                } else if (areaData) {
                  console.log('区级数据已找到，但不是字符串格式')
                }
              }
            }
          } catch (e) {
            console.warn('获取区域名称失败:', e)
          }
        }
      } catch (error) {
        console.error('解析地区编码失败:', error)
      }
    },

    // 客户名称搜索
    handleCustomerSearch(value) {
      if (!value) {
        this.customerSuggestions = []
        return
      }

      // 调用后端接口获取建议列表
      getAction('/crm/customer/suggest', {
        keyword: value,
        limit: 10,
      })
        .then((res) => {
          if (res.success) {
            console.log('获取客户建议列表结果:', res.result)

            // 防止[object Object]显示问题，预处理数据
            this.customerSuggestions = res.result.map((item) => {
              // 确保所有字段有默认值，避免undefined
              const safeItem = {
                id: item.id || '',
                customerCode: item.customerCode || '',
                customerName: item.customerName || '',
                contactPerson: item.contactPerson || '',
                contactPhone: item.contactPhone || '',
                ...item,
              }

              return {
                key: safeItem.id || Math.random().toString(36).substr(2, 10), // 确保有唯一key
                value: safeItem.customerName, // 用于选择时的值
                label: safeItem.customerName, // 用于显示的文本
                customer: safeItem, // 保存完整的客户信息
              }
            })

            console.log('处理后的建议列表:', this.customerSuggestions)
          } else {
            console.error('获取客户建议列表失败:', res.message)
          }
        })
        .catch((err) => {
          console.error('获取客户建议列表出错:', err)
        })
    },

    // 客户名称选择
    handleCustomerSelect(value, option) {
      console.log('选择的客户名称:', value)
      console.log('选择的选项:', option)
      console.log('当前客户建议列表:', this.customerSuggestions)

      // 先通过选择的value查找对应的客户信息
      const selectedCustomer = this.customerSuggestions.find((item) => item.label === value || item.value === value)

      if (selectedCustomer && selectedCustomer.customer) {
        const customer = selectedCustomer.customer
        console.log('选择的客户信息:', customer)

        // 填充客户信息到表单
        const formData = {
          customerCode: customer.customerCode || '',
          customerType: customer.customerType || '',
          industry: customer.industry || '',
          customerSource: customer.customerSource || '',
          creditRating: customer.creditRating || '',
          followUpStatus: customer.followUpStatus || '',
          followUpPerson: customer.followUpPerson || '',
          address: customer.address || '',
          contactPerson: customer.contactPerson || '',
          contactPhone: customer.contactPhone || '',
          position: customer.position || '',
          mobilePhone: customer.mobilePhone || '',
          email: customer.email || '',
          socialContact: customer.socialContact || '',
          gender: customer.gender || '',
        }

        // 设置表单字段值
        this.form.setFieldsValue(formData)

        // 设置省市区（使用新的方法）
        if (customer.provinceCode) {
          this.setAreaData(customer.provinceCode, customer.cityCode, customer.areaCode)
        }

        // 可以选择是否获取该客户的联系人
        this.$confirm({
          title: '提示',
          content: '是否加载该客户的联系人信息？',
          onOk: () => {
            // 获取联系人信息
            getAction(`/crm/contact/list/${customer.id}`)
              .then((res) => {
                if (res.success && res.result && res.result.length > 0) {
                  // 填充第一个联系人的信息
                  const contact = res.result[0]

                  // 直接设置表单值
                  this.form.setFieldsValue({
                    contactPerson: contact.contactName,
                    contactPhone: contact.phone,
                    mobilePhone: contact.mobilePhone,
                    email: contact.email,
                    position: contact.position,
                    socialContact: contact.socialContact,
                    gender: contact.gender,
                  })

                  if (contact.birthday) {
                    this.form.setFieldsValue({
                      birthday: moment(contact.birthday),
                    })
                  }

                  // 打印日志确认联系人信息已成功加载
                  console.log('联系人信息已加载:', contact)
                } else {
                  this.$message.info('未找到该客户的联系人信息')
                }
              })
              .catch((err) => {
                console.error('加载联系人信息失败:', err)
                this.$message.error('加载联系人信息失败')
              })
          },
        })
      } else {
        console.warn('未找到选择的客户信息')
      }
    },

    // 尝试从编码获取地区名称
    tryGetAreaNameByCode(customer) {
      if (!this.$Jpcaa) {
        console.warn('地区编码数据未加载')
        return
      }

      try {
        // 获取省份名称
        if (customer.provinceCode && !this.provinceName) {
          const provinceData = this.$Jpcaa[customer.provinceCode]
          if (typeof provinceData === 'string') {
            this.provinceName = provinceData
          } else if (provinceData) {
            // 如果provinceData是对象，可能需要特殊处理
            console.log('省份数据是对象:', provinceData)
          }
        }

        // 获取城市名称
        if (customer.provinceCode && customer.cityCode && !this.cityName) {
          const provinceData = this.$Jpcaa[customer.provinceCode]
          if (provinceData && typeof provinceData === 'object') {
            const cityData = provinceData[customer.cityCode]
            if (typeof cityData === 'string') {
              this.cityName = cityData
            } else if (cityData) {
              console.log('城市数据是对象:', cityData)
            }
          }
        }

        // 获取区域名称
        if (customer.provinceCode && customer.cityCode && customer.areaCode && !this.areaName) {
          const provinceData = this.$Jpcaa[customer.provinceCode]
          if (provinceData && typeof provinceData === 'object') {
            const cityData = provinceData[customer.cityCode]
            if (cityData && typeof cityData === 'object') {
              const areaData = cityData[customer.areaCode]
              if (typeof areaData === 'string') {
                this.areaName = areaData
              }
            }
          }
        }

        console.log('从编码解析的地区名称:', {
          provinceCode: this.provinceCode,
          provinceName: this.provinceName,
          cityCode: this.cityCode,
          cityName: this.cityName,
          areaCode: this.areaCode,
          areaName: this.areaName,
        })
      } catch (error) {
        console.error('解析地区编码失败:', error)
      }
    },

    // 客户名称变更
    handleCustomerNameChange(value) {
      if (value && value.length > 2 && this.isAdd) {
        // 检查客户名称相似度
        this.checkSimilarCustomer(value)
      }

      // 当联系人已经填写时，检查客户名称和联系人组合的唯一性
      // 使用防抖处理，避免频繁调用
      if (this.checkUniqueTimer) {
        clearTimeout(this.checkUniqueTimer)
      }

      this.checkUniqueTimer = setTimeout(() => {
        if (value && value.trim()) {
          this.checkCustomerUnique()
        }
      }, 500) // 延迟500ms执行
    },

    // 联系人选择或输入改变
    handleContactPersonChange(value) {
      // 当联系人发生变化且客户名称已填写时，检查组合的唯一性
      // 使用防抖处理，避免频繁调用
      if (this.checkUniqueTimer) {
        clearTimeout(this.checkUniqueTimer)
      }

      this.checkUniqueTimer = setTimeout(() => {
        if (value && value.trim()) {
          this.checkCustomerUnique()
        }
      }, 500) // 延迟500ms执行
    },

    // 检查客户名称和联系人组合的唯一性
    checkCustomerUnique() {
      const customerName = this.form.getFieldValue('customerName')
      const contactPerson = this.form.getFieldValue('contactPerson')

      // 当客户名称和联系人都填写了才进行检查
      if (customerName && contactPerson && customerName.trim() && contactPerson.trim()) {
        // 构建检查参数
        const params = {
          customerName: customerName.trim(),
          contactPerson: contactPerson.trim(),
        }

        // 如果是编辑模式，添加id参数
        if (this.model.id) {
          params.id = this.model.id
        }

        // 调用后端接口检查唯一性
        postAction('/crm/customer/checkUnique', params).then((res) => {
          if (!res.success) {
            // 如果已存在，显示警告
            this.$message.warning(res.message)

            // 可以选择让相关字段变红
            this.form.setFields([
              {
                name: 'customerName',
                errors: [res.message],
              },
              {
                name: 'contactPerson',
                errors: [res.message],
              },
            ])
          } else {
            // 清除错误
            this.form.setFields([
              {
                name: 'customerName',
                errors: [],
              },
              {
                name: 'contactPerson',
                errors: [],
              },
            ])
          }
        })
      }
    },

    // 检查相似客户
    checkSimilarCustomer(customerName) {
      if (!customerName) return

      postAction('/crm/customer/checkSimilarity', {
        customerName: customerName,
      })
        .then((res) => {
          if (res.success && res.result && res.result.length > 0) {
            // 确保数据格式正确，处理嵌套的customer对象
            this.similarCustomers = res.result.map((item) => {
              // 确保数据格式完整性
              if (!item.customer) {
                item.customer = {} // 如果customer不存在，创建空对象
              }

              // 返回规范化的数据结构
              return {
                customer: {
                  customerCode: item.customer.customerCode || '',
                  customerName: item.customer.customerName || '',
                  contactPerson: item.customer.contactPerson || '',
                  phone: item.customer.contactPhone || '', // 确保phone字段存在
                  provinceName: item.customer.provinceName || '',
                  cityName: item.customer.cityName || '',
                  areaName: item.customer.areaName || '',
                },
                similarity: item.similarity,
                matchType: item.matchType || 'unknown',
              }
            })

            this.similarCustomerVisible = true
            console.log('已处理的相似客户数据:', this.similarCustomers)
          }
        })
        .catch((err) => {
          console.error('检查相似客户出错:', err)
          this.$message.error('检查相似客户时发生错误')
        })
    },

    // 联系人搜索
    handleContactSearch(value) {
      if (!value) {
        this.contactSuggestions = []
        return
      }

      // 调用后端接口获取联系人建议列表
      getAction('/crm/customer/suggestContact', {
        keyword: value,
        limit: 10,
      })
        .then((res) => {
          if (res.success) {
            // 预处理数据，确保每个项都有必要的字段和类型
            this.contactSuggestions = res.result.map((item) => {
              // 确保所有字段有默认值，避免undefined
              const safeItem = {
                id: item.id || '',
                contactName: item.contactName || '',
                phone: item.phone || '',
                email: item.email || '',
                position: item.position || '',
                ...item,
              }

              return {
                ...safeItem,
                key: safeItem.id || Math.random().toString(36).substr(2, 10), // 添加唯一key
                value: safeItem.contactName || '', // 确保value是字符串
                text: safeItem.contactName || '',
              }
            })
            console.log('处理后的联系人建议列表:', this.contactSuggestions)
          } else {
            console.error('获取联系人建议失败:', res.message)
          }
        })
        .catch((err) => {
          console.error('获取联系人建议出错:', err)
        })
    },

    // 联系人选择
    handleContactSelect(value, option) {
      console.log('选择的联系人:', value)
      console.log('选择的联系人选项:', option)

      // 确保value是字符串类型
      if (typeof value !== 'string') {
        console.warn('联系人选择的值不是字符串类型:', value)
        return
      }

      // 查找选中的联系人信息
      const selectedContact = this.contactSuggestions.find((item) => item.value === value || item.contactName === value)

      if (selectedContact) {
        console.log('找到选中的联系人:', selectedContact)
        // 填充联系人信息到表单
        const contactData = {
          contactPhone: selectedContact.phone || '',
          mobilePhone: selectedContact.mobilePhone || '',
          email: selectedContact.email || '',
          position: selectedContact.position || '',
          socialContact: selectedContact.socialContact || '',
          gender: selectedContact.gender || '',
        }

        // 设置表单字段值
        this.form.setFieldsValue(contactData)

        // 如果有生日，转换为moment对象
        if (selectedContact.birthday) {
          try {
            const birthdayMoment = moment(selectedContact.birthday)
            this.form.setFieldsValue({
              birthday: birthdayMoment,
            })
          } catch (error) {
            console.error('转换生日日期失败:', error)
          }
        }
      } else {
        console.warn('未找到选中的联系人信息')
      }
    },

    // 处理相似客户确认
    handleSimilarCustomerOk() {
      this.similarCustomerVisible = false
      // 可以继续添加客户，用户已确认
    },

    // 处理相似客户取消
    handleSimilarCustomerCancel() {
      this.similarCustomerVisible = false
    },

    // 获取相似度颜色
    getSimilarityColor(similarity) {
      if (similarity >= 90) {
        return '#f5222d' // 红色，高相似度
      } else if (similarity >= 70) {
        return '#fa8c16' // 橙色，中高相似度
      } else if (similarity >= 50) {
        return '#faad14' // 黄色，中等相似度
      } else {
        return '#52c41a' // 绿色，低相似度
      }
    },

    // 手动设置省市区数据
    setAreaData(provinceCode, cityCode, areaCode) {
      if (!provinceCode) return

      try {
        // 构建区域编码数组
        const areaArray = []
        areaArray.push(provinceCode)
        if (cityCode) areaArray.push(cityCode)
        if (areaCode) areaArray.push(areaCode)

        console.log('手动设置区域编码:', areaArray)

        // 设置表单字段值
        this.form.setFieldsValue({ area: areaArray })

        // 保存区域编码
        this.provinceCode = provinceCode
        this.cityCode = cityCode || ''
        this.areaCode = areaCode || ''

        // 初始化区域名称为空
        this.provinceName = ''
        this.cityName = ''
        this.areaName = ''

        // 使用通用方法获取省市区名称
        this.getAreaNamesByCodes()

        console.log('区域名称已设置:', {
          provinceName: this.provinceName,
          cityName: this.cityName,
          areaName: this.areaName,
        })

        // 刷新组件
        if (this.$refs.areaLinkage) {
          this.$nextTick(() => {
            if (typeof this.$refs.areaLinkage.reload === 'function') {
              this.$refs.areaLinkage.reload()
            }
          })
        }
      } catch (error) {
        console.error('设置省市区数据失败:', error)
      }
    },

    // 从区级代码反推完整的省市区名称
    inferAreaNamesFromCodes() {
      if (!this.$Jpcaa) {
        console.warn('地区数据未加载，无法反推省市区名称')
        return false
      }

      try {
        let namesFound = false

        // 首先尝试获取区名称
        if (this.provinceCode && this.cityCode && this.areaCode) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityData = provinceData[this.cityCode]
              if (cityData && typeof cityData === 'object') {
                const areaName = cityData[this.areaCode]
                if (typeof areaName === 'string') {
                  this.areaName = areaName
                  namesFound = true

                  // 当成功获取区名称后，确保也获取省市名称
                  const provinceName = this.$Jpcaa['86'][this.provinceCode]
                  if (provinceName && typeof provinceName === 'string') {
                    this.provinceName = provinceName
                  }

                  const cityName = provinceData[this.cityCode]
                  if (cityName && typeof cityName === 'string') {
                    this.cityName = cityName
                  }
                }
              }
            }
          } catch (e) {
            console.warn('反推区名称失败:', e)
          }
        }

        // 如果无法获取区名称，尝试获取市名称
        if (!namesFound && this.provinceCode && this.cityCode) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityName = provinceData[this.cityCode]
              if (cityName && typeof cityName === 'string') {
                this.cityName = cityName
                namesFound = true

                // 当成功获取市名称后，确保也获取省名称
                const provinceName = this.$Jpcaa['86'][this.provinceCode]
                if (provinceName && typeof provinceName === 'string') {
                  this.provinceName = provinceName
                }
              }
            }
          } catch (e) {
            console.warn('反推市名称失败:', e)
          }
        }

        // 如果无法获取市名称，尝试获取省名称
        if (!namesFound && this.provinceCode) {
          try {
            const provinceName = this.$Jpcaa['86'][this.provinceCode]
            if (provinceName && typeof provinceName === 'string') {
              this.provinceName = provinceName
              namesFound = true
            }
          } catch (e) {
            console.warn('反推省名称失败:', e)
          }
        }

        return namesFound
      } catch (error) {
        console.error('反推省市区名称失败:', error)
        return false
      }
    },

    // 打印当前的省市区数据，用于调试
    logAreaData() {
      console.log('当前省市区数据:', {
        表单area值: this.form.getFieldValue('area'),
        provinceCode: this.provinceCode,
        provinceName: this.provinceName,
        cityCode: this.cityCode,
        cityName: this.cityName,
        areaCode: this.areaCode,
        areaName: this.areaName,
        modelProvinceCode: this.model.provinceCode,
        modelProvinceName: this.model.provinceName,
        modelCityCode: this.model.cityCode,
        modelCityName: this.model.cityName,
        modelAreaCode: this.model.areaCode,
        modelAreaName: this.model.areaName
      })
      
      // 尝试解析区域编码
      if (this.provinceCode && this.$Jpcaa) {
        console.log('解析省级数据:', this.$Jpcaa['86'][this.provinceCode] || '未找到')
        
        if (this.cityCode) {
          console.log('解析市级数据:', (this.$Jpcaa[this.provinceCode] && this.$Jpcaa[this.provinceCode][this.cityCode]) || '未找到')
          
          if (this.areaCode) {
            console.log('解析区级数据:', 
              (this.$Jpcaa[this.provinceCode] && 
               this.$Jpcaa[this.provinceCode][this.cityCode] && 
               this.$Jpcaa[this.provinceCode][this.cityCode][this.areaCode]) || '未找到')
          }
        }
      }
    },
  },
  created() {
    // 扩展联系人字段的验证规则，添加onChange事件
    if (this.validatorRules.contactPerson && this.validatorRules.contactPerson.rules) {
      // 找到现有规则
      const existingRules = this.validatorRules.contactPerson.rules

      // 添加onChange事件处理器
      this.validatorRules.contactPerson.onChange = this.handleContactPersonChange
    }
  },
  mounted() {
    // 确保pcaa数据加载完成
    if (!this.$Jpcaa) {
      console.warn('地区数据未加载，可能会影响省市区选择功能')
    } else {
      console.log('地区数据已加载')
      
      // 如果是编辑模式且有省市区数据，进行处理
      if (!this.isAdd && this.model && this.model.provinceCode) {
        this.$nextTick(() => {
          // 确保数据已经加载完成后再设置
          this.setAreaData(this.model.provinceCode, this.model.cityCode, this.model.areaCode)
        })
      }
    }
  },
  }
</script>

<style scoped>
</style> 